package com.plum.admin.common.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.google.common.collect.Lists;
import com.plum.admin.common.constant.Constant;
import com.plum.admin.common.enums.MenuType;
import com.plum.admin.modules.sys.entity.SysMenu;
import com.plum.admin.modules.sys.vo.MenuTreeVo;
import lombok.experimental.UtilityClass;
import org.springframework.beans.BeanUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @author 子丶沫
 * @version 1.0
 * @date 2021/8/18 11:16
 */
@UtilityClass
public class MenuUtil {

    public void findMenuChildren(List<MenuTreeVo> menuTreeVoList, List<SysMenu> menuList,Integer isLoadButton){
        for (MenuTreeVo menu : menuTreeVoList) {
            List<MenuTreeVo> children= Lists.newArrayList();
            for (SysMenu sysMenu : menuList) {
                if(isLoadButton.equals(1)){
                    if(sysMenu.getType().equals(2)){
                        continue;
                    }
                }
                if(StrUtil.isNotBlank(sysMenu.getParentId())&&menu.getMenuId().equals(sysMenu.getParentId())){
                    MenuTreeVo menuTreeVo=new MenuTreeVo();
                    BeanUtils.copyProperties(sysMenu,menuTreeVo);
                    menuTreeVo.setLabel(sysMenu.getTitle());
                    menuTreeVo.setValue(sysMenu.getId());
                    menuTreeVo.setKey(sysMenu.getId());
                    menuTreeVo.setParentTitle(menu.getTitle());
                    menuTreeVo.setMenuId(sysMenu.getId());
                    if(exists(children,menuTreeVo)){
                        children.add(menuTreeVo);
                    }
                }
            }
            menu.setChildren(children);
            findMenuChildren(children,menuList,isLoadButton);
        }
    }
    private boolean exists(List<MenuTreeVo> menuTreeVoList, MenuTreeVo menuTreeVo){
        boolean exists=false;
        for (MenuTreeVo vo : menuTreeVoList) {
            if(vo.getMenuId().equals(menuTreeVo.getMenuId())){
                exists=true;
                break;
            }
        }
        return !exists;
    }

    /**
     * 构建路由菜单
     * @param jsonArray
     * @param menuList
     * @param parentJson
     */
    public void getRouterArray(JSONArray jsonArray, List<SysMenu> menuList, JSONObject parentJson) {
        for (SysMenu menu : menuList) {
            if(ObjectUtil.isNull(menu.getType())){
                continue;
            }
            String parentId = menu.getParentId();
            JSONObject jsonObject = getPermissionJsonObject(menu);
            if(ObjectUtil.isNull(jsonObject)){
                continue;
            }
            if(parentJson==null&&Constant.PARENT_ID.equals(parentId)){
                jsonArray.add(jsonObject);
                getRouterArray(jsonArray,menuList,jsonObject);
            }else if (parentJson != null &&!Constant.PARENT_ID.equals(parentId)&& parentId.equals(parentJson.getStr("id"))) {
                if (menu.getType().equals(1) || menu.getType().equals(0)) {
                    if (parentJson.containsKey("children")) {
                        parentJson.getJSONArray("children").add(jsonObject);
                    } else {
                        JSONArray children = new JSONArray();
                        children.add(jsonObject);
                        parentJson.putOpt("children", children);
                    }
                    getRouterArray(jsonArray, menuList, jsonObject);
                }
            }
        }
    }
    public JSONObject getPermissionJsonObject(SysMenu permission) {
        JSONObject json = new JSONObject();
        // 类型(0：一级菜单 1：子菜单 2：按钮)
        if (permission.getType().equals(MenuType.BUTTON.getValue())) {
            return null;
        } else if (permission.getType().equals(0) || permission.getType().equals(1)) {
            json.putOpt("id", permission.getId());
            json.putOpt("path", permission.getPath());
            json.putOpt("name", permission.getName());
            if (permission.getParentId().equals(Constant.PARENT_ID)) {
                //一级目录需要加斜杠，不然访问 会跳转404页面
                json.putOpt("component", StrUtil.isEmpty(permission.getComponent()) ? "Layout" : permission.getComponent());
            } else if (!StrUtil.isEmpty(permission.getComponent())) {
                json.putOpt("component", permission.getComponent());
            }
            json.putOpt("redirect", permission.getRedirect());
            JSONObject meta = new JSONObject();
            // 由用户设置是否缓存页面 用布尔值
            meta.putOpt("keepAlive", permission.getKeepAlive());
            meta.putOpt("title", permission.getTitle());
            if (StrUtil.isNotEmpty(permission.getIcon())) {
                meta.putOpt("icon", permission.getIcon());
            }
            if (StrUtil.isNotBlank(permission.getFrameSrc())) {
                meta.putOpt("frameSrc", permission.getFrameSrc());
            }
            meta.putOpt("sort",permission.getSort());
            meta.putOpt("alwaysShow",permission.getAlwaysShow());
            if(StrUtil.isNotBlank(permission.getActiveMenu())){
                meta.putOpt("activeMenu",permission.getActiveMenu());
            }
            if(ObjectUtil.isNotNull(permission.getIsRoot())){
                meta.putOpt("isRoot",permission.getIsRoot());
            }
            meta.putOpt("disabled",permission.getDisabled());
            if(StrUtil.isNotBlank(permission.getPermission())){
                Set<String> set = Arrays.stream(permission.getPermission().split(",")).collect(Collectors.toSet());
                meta.putOpt("permission",set);
            }
            json.putOpt("meta", meta);
        }

        return json;
    }
    /**
     * 判断是否外网URL
     *
     * @return
     */
    private boolean isUrl(String url) {
        return url != null && (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("{{"));
    }

    /**
     * 路由名称
     * @param url
     * @return
     */
    private String urlToRouteName(String url) {
        if (StrUtil.isNotEmpty(url)) {
            int i = url.lastIndexOf("/");
            return url.substring(i + 1);
        } else {
            return null;
        }
    }
}
